<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
//引入模型
use App\Admin\Admin;
//引入input
use Input;
// use Auth;
use DB;
//引入session
use Session;
use Action;
use Event;
//引入Hash
use Hash;

class AdminController extends Controller
{

    //显示日志记录
    public function action(){
        //$dd = Session::get('login_admin_59ba36addc2b2f9401580f014c7f58ea4e30989d');
        //获取数据
        // $data = DB::table('action') -> get();
        //dd($dd);
        // Session::put('key', 'value');
        // login_admin_59ba36addc2b2f9401580f014c7f58ea4e30989d
        // login_admin_59ba36addc2b2f9401580f014c7f58ea4e30989d" => 1
        
         //日志记录==S
        

            $actions = [
                // 'id'          => 'null',   
                'action_name' => '查看日志记录',
                'action_time' => date('Y-m-d H:i:s'),
                'action_biao' => 'ib_admin',
                'action_project' => '',
                'admin_id'    => Session::get('login_admin_59ba36addc2b2f9401580f014c7f58ea4e30989d')
            ];
            DB::table('action') -> insert($actions);

        //日志记录==E

        // $data = DB::table('action') -> get();
        
        $data = \App\Admin\Action::all();

        return view('admin.admin.action',compact('data'));
    }



    //批量删除
    public function deletes(){

        $str = Input::get('id');

        // dd($str);
        // $str = ltrim(',',$str);
        // dd($str);
        // $ids = explode(',', $str);
        // $ss = '';
        // foreach ($ids as $key => $value) {
        //     $ss 
        // }
        $ss = "(" . $str . ")"; 
        // dd($ss);

        //dd("update ib_admin set deleted_at = 1 where id in ".$ss." ");

        if( DB::statement("update ib_admin set deleted_at = 2 where id in $ss")){

            //日志记录==S
            $actions = [
                // 'id'          => 'null',   
                'action_name' => '批量删除用户',
                'action_time' => date('Y-m-d H:i:s'),
                'action_biao' => 'ib_admin',
                'action_project' => $str,
                'admin_id'    => Session::get('login_admin_59ba36addc2b2f9401580f014c7f58ea4e30989d')
            ];
            DB::table('action') -> insert($actions);
            //日志记录==E


            return '1';
        }else{
            return '0';
        }

        


    }


    //停用
    public function start(){

        // $id = Input::get('id');
        // $result = Admin::where('id','=',$id) -> update(['status' => '2']);

        // return $result ? '1' : '0';

        $id = Input::get('id');
        $result = Admin::where('id','=',$id) -> update(['status' => '2']);


         //日志记录==S
        $actions = [
            // 'id'          => 'null',   
            'action_name' => '启用用户',
            'action_time' => date('Y-m-d H:i:s'),
            'action_biao' => 'ib_admin',
            'action_project' => $id,
            'admin_id'    => Session::get('login_admin_59ba36addc2b2f9401580f014c7f58ea4e30989d')
        ];
        DB::table('action') -> insert($actions);
        //日志记录==E
        
        return $id;

    }


    //停用
    public function stop(){

        // $id = Input::get('id');
        // $result = Admin::where('id','=',$id) -> update(['status' => '1']);
        // return $result ? '1' : '0';
        
        $id = Input::get('id');
        $result = Admin::where('id','=',$id) -> update(['status' => '1']);

         //日志记录==S
        $actions = [
            // 'id'          => 'null',   
            'action_name' => '禁用用户',
            'action_time' => date('Y-m-d H:i:s',time()),
            'action_biao' => 'ib_admin',
            'action_project' => $id,
            'admin_id'    => Session::get('login_admin_59ba36addc2b2f9401580f014c7f58ea4e30989d')
        ];
        DB::table('action') -> insert($actions);
        //日志记录==E
        // dd(date('Y-m-d H:i:s',time()));

        return $id;
        

    }


    //编辑管理员
    public function edit(){

        if(Input::method() == 'POST'){

            $pwd = bcrypt(Input::get('password'));
            $id = Input::get('id');
            // dd($id);

            $data = Input::except('_token','password2','password');

            $data['password'] = $pwd;
            $data['deleted_at'] = 1;
            $data['created_at'] = date('Y-m-d H:i:s');

            // $data = {'password' => bcrypt($pwd)}s;

            $result = Admin::where('id','=',$id) -> update($data);


            //日志记录==S
            $actions = [
                // 'id'          => 'null',   
                'action_name' => '修改用户',
                'action_time' => date('Y-m-d H:s:i'),
                'action_biao' => 'ib_admin',
                'action_project' => $id,
                'admin_id'    => Session::get('login_admin_59ba36addc2b2f9401580f014c7f58ea4e30989d')
            ];
            DB::table('action') -> insert($actions);
            //日志记录==E



            return $result ? '1' : '0';
            

        } else {

            $id = Input::get('id');
            $data = Admin::where('id','=',$id) -> get();
            // dd($data);
             $role_data = \App\Admin\Role::all();
            //显示待修改的表单
            return view('admin.admin.edit',compact('data','role_data'));

        }

    }


    //添加管理员
    public function add(){

        if(Input::method() == 'POST'){

            $pwd = bcrypt(Input::get('password'));
            // dd($pwd);

            $data = Input::except('_token','password2','password');

            $data['password'] = $pwd;
            $data['deleted_at'] = 1;
            $data['created_at'] = date('Y-m-d H:i:s');

            // $data = {'password' => bcrypt($pwd)}s;

            // $result = Admin::insert($data);
            $result = Admin::insertGetId($data);

             //日志记录==S
            $actions = [
                // 'id'          => 'null',   
                'action_name' => '添加用户',
                'action_time' => date('Y-m-d H:s:i'),
                'action_biao' => 'ib_admin',
                'action_project' => $result,
                'admin_id'    => Session::get('login_admin_59ba36addc2b2f9401580f014c7f58ea4e30989d')
            ];
            DB::table('action') -> insert($actions);
            //日志记录==E

            return $result ? '1' : '0';

        }else{

            $data = \App\Admin\Role::all();


            return view('admin.admin.add',compact('data'));

        }

    }

    
    //软删除
    public function del(){
        // $res = Auth::guard('admin') -> user();
        // dd($res);

        // dd(Input::get('id'));

        $id = Input::get('id');

        $result = Admin::where('id','=',$id) -> update(['deleted_at' => 2]);


        //日志记录==S
       

        $action = new \App\Admin\Action;

        // $action -> action =  [
        //     // 'id'          => 'null',   
        //     'action_name' => '伪删除',
        //     'action_time' => date('Y-m-d H:s:i'),
        //     'action_biao' => 'ib_admin',
        //     'action_project' => $id,
        //     'admin_id'    => Session::get('login_admin_59ba36addc2b2f9401580f014c7f58ea4e30989d')
        // ];
        
        $action -> action_name = '伪删除';
        $action -> action_time = date('Y-m-d H:i:s');
        $action -> action_biao = 'ib_admin';
        $action -> action_project = $id;
        $action -> admin_id = Session::get('login_admin_59ba36addc2b2f9401580f014c7f58ea4e30989d');

        Event::fire(new \App\Events\PostSaved($action));

        // DB::table('action') -> insert($actions);
        //日志记录==E

       return $result ? '1' : '0';
        
    }



    //serverSide展示服务端分页
    public function serverSide($mark = ''){
    	//判断是否是ajax请求
    	if($mark == 'isAjax'){
    		//接收排序的参数
    		$orderByIndex = Input::get('order.0.column');//接收order[0][column]元素的值
    		$orderRule = Input::get('order.0.dir');	//获取order[0][dir]的元素值
    		//定义DT索引与字段的关系映射
    		$_map = [
    			1	=>	'id',
    			2	=>	'username',
    			3	=>	'mobile',
    			4	=>	'email',
    			5	=>	'role_id',
    			6	=>	'created_at',
    			7	=>	'status'
    		];
    		$orderByFieldName = $_map[$orderByIndex];//获取字段名
    		//接收分页参数
    		$start = Input::get('start');//起始位置
    		$length = Input::get('length');//偏移量
    		//获取搜索的关键词
    		$keyword = Input::get('search.value');

            $data = Admin::orderBy($orderByFieldName,$orderRule) -> offset($start) -> limit($length) -> where('username','like',"%$keyword%") -> where('deleted_at','=','1') -> get();

            foreach ($data as $key => $value) {
                $value -> role;
            }

    		//ajax请求
    		return response() -> json([
    			'draw'				=>	(int) Input::get('draw'),//请求计数器
    			'recordsTotal'		=>	Admin::count(),//数据表中总的记录数
    			'recordsFiltered'	=>	Admin::where('username','like',"%$keyword%") -> count(),//被过滤之后的记录数
    			'data'				=>	$data//查询到的数据对象
    		]);
    	}else{

            //日志记录==S
            $actions = [
                // 'id'          => 'null',   
                'action_name' => '查看管理员表',
                'action_time' => date('Y-m-d H:i:s'),
                'action_biao' => 'ib_admin',
                'action_project' => '',
                'admin_id'    => Session::get('login_admin_59ba36addc2b2f9401580f014c7f58ea4e30989d')
            ];
            DB::table('action') -> insert($actions);
            //日志记录==E

    		//展示视图
    		return view('admin.admin.serverSide');
    	}
    }

    //服务端管理员 修改 密码
    public function mima() {

         if(Input::method() == 'POST'){
            //管理员输入的旧密码
            $oldpassword = Input::get('oldpassword');
            //管理员输入的新密码
            $newpassword = Input::get('newpassword');
            //获取要修改的管理员的 id
            $id = Input::get('id');
            //获取要修改的管理员的数据库里面的 密码
            $password = Admin::where('id','=',$id) -> value('password');
            //先判断旧密码是否正确
            if(!Hash::check($oldpassword, $password)) {
                return '2';
            }
            //对新密码进行保存
            $update  = ['password' => bcrypt($newpassword)];
            $result = Admin::where('id','=',$id) -> update($update);

            return $result ? '1' : '0';

            // if($result) {
            //     return '1';
            // }else{
            //     return '';
            // }


         }else{

            $idmi = Input::get('id');

            return view('admin.admin.mima') -> with('idmi',$idmi);

         }

    }




    //index，展示管理员列表的方法
    public function index(){
        //获取数据（用get也可以）
        $data = Admin::all();

        //对删除的行为进行记录
        //$action['admin_id'] = Auth::guard('admin') -> user() -> get('id');
       // dd($action);
        //\App\Admin\Action::insert($action);


        //展示模版
        return view('admin.admin.index',compact('data'));
    }


}
